package com.glacier.yuyuan.common.utils;

import com.glacier.common.support.domain.UserInfo;
import com.glacier.common.support.utils.SpringContextHolder;
import com.glacier.yuyuan.modules.admin.sys.domain.User;
import com.glacier.yuyuan.modules.admin.sys.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * date 2022-11-10 10:46
 * 权限工具类
 *
 * @author glacier
 * @version 1.0
 */
public class SecurityUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(SecurityUtils.class);

    private SecurityUtils() {
    }

    /**
     * 获取当前用户id
     *
     * @return
     */
    public static String getCurrentUserId() {
        String userId = "";
        Authentication authentication = SecurityContextHolder.getContext()
                .getAuthentication();
        if (authentication == null || authentication instanceof AnonymousAuthenticationToken) {
            LOGGER.info("authentication 匿名, {}", authentication);
            return userId;
        }
        Object principal = authentication.getPrincipal();
        if (principal == null) {
            LOGGER.info("principal 为空, {}", authentication);
            return userId;
        }
        if (principal instanceof UserInfo) {
            userId = ((UserInfo) principal).getId();
            return userId;
        }
        LOGGER.info("authentication 其他, {}", authentication);
        return userId;
    }

    /**
     * 获取当前用户
     *
     * @return
     */
    public static User getCurrentUser() {
        String userId = getCurrentUserId();
        if (userId.isBlank()) {
            return new User();
        }
        UserService userService = SpringContextHolder.getBean(UserService.class);
        return userService.findById(userId);
    }
}
